home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 8325 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: news.eden.com!usenet
  2. From: Shane Sadler <nexus@eden.com>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Why is Gets() so bad?
  5. Date: Sat, 02 Mar 1996 23:34:42 -0700
  6. Organization: Eden Matrix Services
  7. Message-ID: <31393D81.271EBFCD@eden.com>
  8. References: <4hb1ie$pa7@ixnews2.ix.netcom.com>
  9. NNTP-Posting-Host: net-1-039.austin.eden.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (X11; I; Linux 1.2.8 i586)
  14.  
  15. Studcat's Big Studdog. wrote:
  16. > Hi.. I'm not a newbie.. I don't even use Gets(), fgets(), or scanf.. I
  17. > use my own getstring function. My question is that everywhere I see
  18. > that gets() is bad. Why exactly is it so bad? Could someone please
  19. > explain in more detail than what the FAQ does? Thanks.
  20.  
  21. You've *never* used scanf(), et al.?! Hmmmm.... If you know anything
  22. about memory allocation in C (and you should if you went to the trouble
  23. to write your own function to avoid some of these problems), it should
  24. be obvious why the use of something like gets() is not desirable. Maybe
  25. you should use some of those functions just to fill in that strange
  26. lacuna in your C education.
  27.  
  28. In more detail than the FAQ? Well, actually, not much detail is needed.
  29. How about if I quote the Ten Commandments for C Programmers:
  30.  
  31. [quote]
  32. V. Thou shalt check the array bounds of all strings (indeed, all
  33. arrays), for surely where thou typest "foo" somone someday shall type
  34. "supercalifragilisticexpialidocious". 
  35. [end quote]
  36.  
  37. Basically, gets() doesn't prevent a user from overstepping those bounds.
  38. So its use can cause you a lot of problems if someone were to type in
  39. that long entry above and you have made provisions only for a few bytes.
  40. The function fgets(), on the other hand, explicitly sets the maximum
  41. input allowed so the bounds are not exceeded. That's not much detail,
  42. but it's the whole story. I hope it helps.
  43.  
  44. BTW, if anyone is interested in Henry Spencer's annotated version of the
  45. Ten Commandments for C Programmers, I believe it's still available at
  46. ftp.spies.com. Look in /Library/Techdoc/Language. A most excellent
  47. document. Ignore the advice therein at your own peril.
  48.  
  49. -- Shane
  50. ===================================================================
  51. S. M. Sadler
  52. e-mail: nexus@eden.com
  53. Web: http://www.eden.com/~nexus
  54.